package sysAuth

import initConfig.SysInitData
import sysUtil.ResultCode
import sysUtil.ResultJson
import sysUtil.SysAuthSQL
import sysUtil.SysCommUtil
import xdInterface.XdControllerInterface

class SysNoticeController implements XdControllerInterface {


    def authUtilsService
    def sysDBUtilService

    def index() {query()}

    @Override
    def delete() {
        def result = ResultJson.resultJson()
        try {
            def userNo = params.userNo
            def user = SysUsers.findByUserNo(userNo)
            def userGrade = authUtilsService.isAvailable(user)
            def  id = Long.parseLong(String.valueOf(params?.id))
            def list = authUtilsService.getAllNoticeById(id,null)
            list.each {
                def notice =   SysNotice.get(it.ID)
                if(notice.type == "0"){//公告
                    def sysNoticeRela = SysNoticeRela.findAllByNoticeId(notice.id)
                    sysNoticeRela.each{iti->
                        //def releIt = SysNoticeRela. sysNoticeRela.get(iti.id)
                        iti.delete(flush: true)
                    }
                    notice.setDelFlag("1")
                    notice.save(flush: true)
                }else {//私信
                    if(notice.toUser == userNo ||
                            SysInitData.USER_GRADE_ADMIN_DATA.contains(userGrade)){
                        notice.setDelFlag("1")
                        notice.save(flush: true)
                    }
                }
            }
            result.put(ResultJson.CODE.name,ResultCode.OPT_SUCCESS.code)
            result.put(ResultJson.MSG.name,ResultCode.OPT_SUCCESS.message)
        }
        catch (Exception e){
            result.put(ResultJson.CODE.name,ResultCode.OPT_ERROR.code)
            result.put(ResultJson.MSG.name,ResultCode.OPT_ERROR.message)
            e.printStackTrace()
        }finally{
            render result
        }
    }

    @Override
    def detail() {
        return null
    }

    @Override
    def del() {
        delete()
    }

    @Override
    def edit() {
        return null
    }

    @Override
    def save() {
        return null
    }

    @Override
    def update() {
        def result = ResultJson.resultJson()
        try {
            def id =  params?.id
            def type = params.type?:""
            def toUserNo = params.userNo
            def userGrade = authUtilsService.isAvailable(SysUsers.findByUserNo(toUserNo))
            if(id){
                id = Long.parseLong(String.valueOf(id))
                def list = authUtilsService.getAllNoticeById(id,null)
                list.each {
                    if(it.STATE=="1"){
                        if( it.TYPE== "1" && it.TO_USER == toUserNo){//私信
                            def notice = SysNotice.get(it.ID)
                            notice.setState("0")
                            notice.save(flush: true)
                        }else if( it.TYPE== "0" ){//否则是公告
                            def notice = SysNotice.get(it.ID)
                            notice.setState("0")
                            notice.save(flush: true)
                        }
                    }
                }
            }else {
                SysNotice.findAllByStateAndType("1",type)?.each {
                    if(it.state == "1"){
                        if(type=="1"){//私信
                            if(it.toUser == toUserNo){
                                it.setState("0")
                                it.save(flush: true)
                            }
                        }else{//公告直接更新
                            //公告谁创建的，谁才可以更新
                            if(it.creator == toUserNo || SysInitData.USER_GRADE_ADMIN_DATA.contains(userGrade)){//超级管理员，直接更新
                                it.setState("0")
                                it.save(flush: true)
                            }
                        }
                    }
                }
            }
            result.put(ResultJson.CODE.name,ResultCode.OPT_SUCCESS.code)
            result.put(ResultJson.MSG.name,ResultCode.OPT_SUCCESS.message)
        }
        catch (Exception e){
            result.put(ResultJson.CODE.name,ResultCode.OPT_ERROR.code)
            result.put(ResultJson.MSG.name,ResultCode.OPT_ERROR.message)
            e.printStackTrace()
        }finally{
            render result
        }
    }

    @Override
    def add() {
        def result = ResultJson.resultJson()
        try {
            def type =  params.TYPE?:"0"//公告
            def state =  params.STATE?:"1"//未读
            def title =  params.TITLE?:"New Notice"//标题
            def remainDay = Integer.parseInt(params.REMAIN_DAY?:"9999999")
            def parentId =  params?.PARENT_ID
            def toUser =  params?.TO_USER
            def content = params?.CONTENT
            def orgId = params?.orgId
            def user = SysUsers.findByUserNo(params.userNo)

            def notice = new SysNotice(title: title,content: content,state: state,type: type,
                    parentId:parentId,toUser: toUser,remainDay: remainDay,creator: params.userNo)
            notice.save(flush: true)
            if(orgId){
                orgId = String.valueOf(orgId).split(",")
                orgId.each {
                    def rr = new SysNoticeRela(orgId: it,noticeId: notice.id)
                    rr.save(flush: true)
                }
            }else{
                def data = []
                if(SysInitData.USER_GRADE_ADMIN_DATA.contains(authUtilsService.isAvailable(user))){
                    data = SysOrganization.list()?.id
                }else{
                    data = authUtilsService.listDataByUserAndRoleType(user,SysInitData.DATA_ROLE)?.dataId.unique()
                }
                if (data){
                    data.each {
                        def rr = new SysNoticeRela(orgId: it,noticeId: notice.id)
                        rr.save(flush: true)
                    }
                }
            }
            result.put(ResultJson.CODE.name,ResultCode.OPT_SUCCESS.code)
            result.put(ResultJson.MSG.name,ResultCode.OPT_SUCCESS.message)
        }
        catch (Exception e){
            result.put(ResultJson.CODE.name,ResultCode.OPT_ERROR.code)
            result.put(ResultJson.MSG.name,ResultCode.OPT_ERROR.message)
            e.printStackTrace()
        }finally{
            render result
        }
    }

    /**
     * 写私信
     * @return
     */
    def addPrivate(){
        def result = ResultJson.resultJson()
        try {
            def type =  params.TYPE?:"1"//私信
            def state =  params.STATE?:"1"//未读
            def title =  params.TITLE?:"New Notice"//标题
            def remainDay = Integer.parseInt(params.REMAIN_DAY?:"9999999")
            def parentId =  params?.PARENT_ID
            def toUser =  params?.toUser
            def content = params?.CONTENT

            if(toUser){
                String.valueOf(toUser).split(",").each {
                    def notice = new SysNotice(title: title,content: content,state: state,type: type,
                            parentId:parentId,toUser: it,remainDay: remainDay,creator: params.userNo)
                    notice.save(flush: true)
                }
            }
            result.put(ResultJson.CODE.name,ResultCode.OPT_SUCCESS.code)
            result.put(ResultJson.MSG.name,ResultCode.OPT_SUCCESS.message)
        }
        catch (Exception e){
            result.put(ResultJson.CODE.name,ResultCode.OPT_ERROR.code)
            result.put(ResultJson.MSG.name,ResultCode.OPT_ERROR.message)
            e.printStackTrace()
        }finally{
            render result
        }
    }

    @Override
    def dowLoad() {
        return null
    }

    @Override
    def upLoad() {
        return null
    }

    @Override
    def query() {
        def result = ResultJson.resultJson()
        try {

            def user = SysUsers.findByUserNo(params.userNo)
            def type =  params.type?:"0"

            def sql = SysAuthSQL.getNoticeSql(user.userNo,null,params?.type,authUtilsService.isAvailable(user),null)
            def offset = Integer.parseInt(String.valueOf(params.page?:"1"))
            def max = Integer.parseInt(String.valueOf(params.limit?:"10"))
            def list = sysDBUtilService.pageResult(sql,offset,max,sysDBUtilService.getGroovySqlInstance())
            def count = sysDBUtilService.pageCount(sql,sysDBUtilService.getGroovySqlInstance())

            result.put(ResultJson.COUNT.name,count)
            result.put(ResultJson.DATA.name,list)
            result.put(ResultJson.CODE.name,ResultCode.TABLE_DATA_SUCCESS.code)
            result.put(ResultJson.MSG.name,ResultCode.TABLE_DATA_SUCCESS.message)

        }
        catch (Exception e){
            result.put(ResultJson.CODE.name,ResultCode.QUERY_ERROR.code)
            result.put(ResultJson.MSG.name,ResultCode.QUERY_ERROR.message)
            e.printStackTrace()
        }finally{
            render result
        }
    }

    @Override
    def getOne() {
        return null
    }


    /**
     * 首页消息数量
     * @return
     */
    def indexNoticeCount(){
        def result = ResultJson.resultJson()
        try {

            def user = SysUsers.findByUserNo(params.userNo)
            SysFunctions function = SysFunctions.findByFuncNo("SYS_NOTICE")
            params.type = "0"
            def count1 = authUtilsService.getIndexNoticeCountByType(params)
            params.type = "1"
            def count2 = authUtilsService.getIndexNoticeCountByType(params)

            result.put(ResultJson.COUNT.name,count1 + count2)
            result.put(ResultJson.DATA.name,SysCommUtil.domainToMap(function))
            result.put(ResultJson.CODE.name,ResultCode.TABLE_DATA_SUCCESS.code)
            result.put(ResultJson.MSG.name,ResultCode.TABLE_DATA_SUCCESS.message)

        }
        catch (Exception e){
            result.put(ResultJson.CODE.name,ResultCode.QUERY_ERROR.code)
            result.put(ResultJson.MSG.name,ResultCode.QUERY_ERROR.message)
            e.printStackTrace()
        }finally{
            render result
        }
    }

    /**
     * 根据ID获取all notice
     * @param id
     * @return
     */
    def listAllNoticeById(){
        def result = ResultJson.resultJson()
        try {
            def id = params?.id
            def list = authUtilsService.getAllNoticeById(id,null)
            result.put(ResultJson.DATA.name,list)
            result.put(ResultJson.CODE.name,ResultCode.TABLE_DATA_SUCCESS.code)
            result.put(ResultJson.MSG.name,ResultCode.TABLE_DATA_SUCCESS.message)
        }
        catch (Exception e){
            result.put(ResultJson.CODE.name,ResultCode.QUERY_ERROR.code)
            result.put(ResultJson.MSG.name,ResultCode.QUERY_ERROR.message)
            e.printStackTrace()
        }finally{
            render result
        }
    }

    /**
     * 设置私信标识
     * @return
     */
    def setPrivateNotice(){
        def result = ResultJson.resultJson()
        try {

            def user = SysUsers.findByUserNo(params.userNo)
            def count2 = authUtilsService.getIndexNoticeCountByType(params)
            //result.put(ResultJson.COUNT.name, count2)
            result.put(ResultJson.DATA.name,count2)
            result.put(ResultJson.CODE.name,ResultCode.TABLE_DATA_SUCCESS.code)
            result.put(ResultJson.MSG.name,ResultCode.TABLE_DATA_SUCCESS.message)

        }
        catch (Exception e){
            result.put(ResultJson.CODE.name,ResultCode.QUERY_ERROR.code)
            result.put(ResultJson.MSG.name,ResultCode.QUERY_ERROR.message)
            e.printStackTrace()
        }finally{
            render result
        }
    }

}
